package com.zzw.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzw.springboot.bean.Product;
import com.zzw.springboot.bean.SysUser;
import com.zzw.springboot.service.ProductService;
import com.zzw.springboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品控制器
 */
@Controller
@RequestMapping("/product")
public class ProductController extends BaseController {

    @Autowired
    private ProductService productService;

    /**
     * 查询商品列表
     */
    @GetMapping("/list")
    @ResponseBody
    public Result listProducts(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "10") Integer pageSize,
                           Product product) {

        //创建lambdaQueryWrapper, 封装查询条件
        LambdaQueryWrapper<Product> lambdaQueryWrapper = Wrappers.<Product>lambdaQuery();
        if (StringUtils.hasText(product.getProductName())) {
            SFunction<Product, Object> sf = Product::getProductName;
            lambdaQueryWrapper.like(sf, product.getProductName());
        }
        if (product.getCategoryId() != null) {
            SFunction<Product, Object> sf = Product::getCategoryId;
            lambdaQueryWrapper.eq(sf, product.getCategoryId());
        }
        if (product.getStatus() != null) {
            SFunction<Product, Object> sf = Product::getStatus;
            lambdaQueryWrapper.eq(sf, product.getStatus());
        }
        Page<Product> page = productService.page(new Page<Product>(pageNum, pageSize), lambdaQueryWrapper);
        return Result.success(page);
    }

    /**
     * 获取商品详情
     */
    @GetMapping("/{productId}")
    @ResponseBody
    public Result getProductInfo(@PathVariable Integer productId) {
        Product product = productService.getProductById(productId);
        if (product != null) {
            return Result.success(product);
        } else {
            return Result.error("商品不存在");
        }
    }

    /**
     * 添加商品
     */
    @PostMapping("/add")
    @ResponseBody
    public Result addProduct(@Validated @RequestBody Product product, Errors errors) {
        // 表单验证
        Map<String, Object> errorMap = validateProduct(errors);
        if (!errorMap.isEmpty()) {
            return Result.error(errorMap,"表单验证失败");
        }

        // 检查商品编码是否已存在
        if (productService.checkProductCodeExists(product.getProductCode(), null)) {
            return Result.error("商品编码已存在");
        }

        // 保存商品
        if (productService.addProduct(product)) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    /**
     * 更新商品
     */
    @PutMapping("/update")
    @ResponseBody
    public Result updateProduct(@Validated @RequestBody Product product, Errors errors) {
        // 表单验证
        Map<String, Object> errorMap = validateProduct(errors);
        if (!errorMap.isEmpty()) {
            return Result.error(errorMap,"表单验证失败");
        }

        // 检查商品ID是否存在
        if (product.getProductId() == null) {
            return Result.error("商品ID不能为空");
        }

        // 检查商品是否存在
        Product existProduct = productService.getProductById(product.getProductId());
        if (existProduct == null) {
            return Result.error("商品不存在");
        }

        // 检查商品编码是否已存在（排除自身）
        if (productService.checkProductCodeExists(product.getProductCode(), product.getProductId())) {
            return Result.error("商品编码已存在");
        }

        // 更新商品
        if (productService.updateProduct(product)) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/delete/{productId}")
    @ResponseBody
    public Result deleteProduct(@PathVariable Integer productId) {
        // 检查商品是否存在
        Product product = productService.getProductById(productId);
        if (product == null) {
            return Result.error("商品不存在");
        }

        // 删除商品
        if (productService.deleteProduct(productId)) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 批量删除商品
     */
    @DeleteMapping("/batchDelete")
    @ResponseBody
    public Result batchDeleteProducts(@RequestBody Integer[] productIds) {
        if (productIds == null || productIds.length == 0) {
            return Result.error("请选择要删除的商品");
        }

        // 批量删除
        if (productService.deleteProductBatch(productIds)) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }

    /**
     * 导入商品
     */
    @PostMapping("/import")
    @ResponseBody
    public Result importProducts(@RequestParam(value = "file") MultipartFile file) {
        return importData(file, "product");
    }

    /**
     * 导出商品
     */
    @GetMapping("/export")
    public void exportProducts(HttpServletResponse response,
                               @RequestParam(required = false) String productName,
                               @RequestParam(required = false) Integer categoryId,
                               @RequestParam(required = false) Integer status) {
        Map<String, Object> searchParams = new HashMap<>();
        if (productName != null) searchParams.put("productName", productName);
        if (categoryId != null) searchParams.put("categoryId", categoryId);
        if (status != null) searchParams.put("status", status);

        exportData(response, "product", searchParams);
    }

    /**
     * 验证商品表单
     */
    private Map<String, Object> validateProduct(Errors errors) {
        Map<String, Object> errorMap = new HashMap<>();
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return errorMap;
    }
}
